<!--
 * @Author: lh
 * @Date: 2023-07-11 13:52:31
 * @LastEditors: lh
 * @LastEditTime: 2023-10-19 14:28:09
-->
<template>
  <div>
    <!-- :searchDataList="searchDataListJy" -->
    <!-- <personnel></personnel> -->
    <tabCom
      @Refresh="Refresh"
      @search-callback="searchCallback"
      :title="'收函接收/著录/导入'"
      :operation-api="operationApiA"
      :table-data-rule="tableDataRuleA"
      :search-data-list="searchDataListJy"
      :needPagination="true"
      :update_show_key="'id'"
      :update_show_value="[0]"
      :formDataWidth="'30%'"
      :showDownloadTem="true"
      :showUpload="true"
      :addButtonList="addButtonList"
      :isAddAjaxData="true"
      :addAjaxData="{ lettersState: iszjFfa, batchDivisionInfo: JSON.stringify(batchDivisionInfoVal) }"
      @buttonMoudle="buttonMoudle"
      ref="tabCombox"
    >
      <template #add="{ formData }">
        <el-form-item :label="item.title" v-for="(item, index) in searchDataListJyEdit" :key="index">
          <el-input v-if="!item.type" v-model="formData[item.name]" placeholder="请输入" />
          <personnel v-model="formData[item.name]" v-else-if="item.type == 'user'"></personnel>

          <batch v-model="formData[item.name]" v-else-if="item.type == 'batch'"></batch>
          <div v-else-if="item.type == 'batchNew'">
            <el-radio-group v-model="iszjFfa" class="ml-4">
              <el-radio :label="0" size="large">总监分发</el-radio>
              <el-radio :label="4" size="large">主办人分发</el-radio>
            </el-radio-group>
            <personnel v-model="fenfaVal"></personnel>
          </div>
          <el-input
            v-else-if="item.type == 'number'"
            type="number"
            v-model="formData[item.name]"
            placeholder="请输入"
          />
          <!-- value-format="YYYY/MM/DD" -->
          <el-date-picker
            v-else-if="item.type == 'timeday'"
            v-model="formData[item.name]"
            type="date"
            format="YYYY/MM/DD"
            placeholder="请选择"
          />
          <el-date-picker
            v-else-if="item.type == 'datetime'"
            v-model="formData[item.name]"
            type="datetime"
            format="YYYY/MM/DD HH:mm:ss"
            placeholder="请选择"
          />
          <upfilebox
            v-else-if="item.type == 'file'"
            fileType="file"
            v-model="formData[item.name]"
            v-model:name="formData[item.prop]"
          ></upfilebox>
          <el-date-picker
            @change="chooseTimeChange(formData[item.name])"
            v-else-if="item.type == 'time'"
            v-model="formData[item.name]"
            type="datetimerange"
            format="YYYY/MM/DD"
            value-format="YYYYMMDD"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
          <el-select
            v-else-if="item.type == 'select' && item!.list!.length > 0"
            v-model="formData[item.name]"
            default-first-option
            :reserve-keyword="false"
            clearable
            allow-create
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="items in item.list"
              :key="items.value"
              :label="items.label || items.name"
              :value="items.value || items.id"
            />
          </el-select>
          <el-select
            v-else-if="item.type == 'selectLable'"
            v-model="formData[item.name]"
            default-first-option
            :reserve-keyword="false"
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="items in item.list"
              :key="items.value"
              :label="items.label || items.name"
              :value="items.label || items.name"
            />
          </el-select>
          <el-select
            v-else-if="item.type == 'multipleSelect'"
            multiple
            v-model="formData[item.name]"
            default-first-option
            :reserve-keyword="false"
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="items in item.list"
              :key="items.value"
              :label="items.label || items.name"
              :value="items.label || items.name"
            />
          </el-select>
        </el-form-item>
      </template>
      <template #batchbox="{ data }">
        <div style="width: 100%; position: relative">
          <el-steps
            :active="data.lettersState == 4 ? 2 : data.lettersState != 3 ? data.lettersState - 1 : 3"
            :align-center="true"
            finish-status="success"
          >
            <el-step title="总监分发" />
            <el-step title="部门分发" />
            <el-step title="主办人接收" />
          </el-steps>
        </div>
      </template>
    </tabCom>
    <!-- 导入弹框 -->
    <el-dialog v-model="dialogVisible" :title="'导入弹框'" @close="resetForm" width="30%">
      <el-form ref="formRef" label-width="100px" label-position="left">
        <el-form-item prop="actionItemEvolve" label="处理方式">
          <el-input v-model="actionItemEvolve" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
    <!-- 总监分发 -->
    <el-dialog v-model="zjFfData.dialogVisible" :title="'总监分发'" @close="resetFormzjFfData" width="30%">
      <el-form ref="formRef" label-width="100px" label-position="left">
        <el-form-item label="设置分发类型">
          <el-radio-group v-model="zjFfData.distributionType" class="ml-4">
            <el-radio :label="1" size="large">分发到部门</el-radio>
            <el-radio :label="2" size="large">分发到主办人</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="zjFfData.distributionType == 1 ? '部门负责人' : '主办人'">
          <personnel v-model="zjFfData.distributionUserId"></personnel>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="zjFfData.dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="CloseTaskFnConfim">确认</el-button>
      </template>
    </el-dialog>
    <!-- 部门分发 -->
    <el-dialog v-model="zbFfData.dialogVisible" :title="'部门分发'" @close="resetFormzbFfData" width="30%">
      <el-form ref="formRef" label-width="100px" label-position="left">
        <el-form-item :label="'主办人'">
          <personnel v-model="zbFfData.sponsorUserId"></personnel>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="zbFfData.dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="validationFnConfim">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import tabCom from "@/components/table/indexcopy.vue"
// import { gethomeStatistics } from "@/api/home/index"
import { ref, onMounted, watch, reactive } from "vue"
import upfilebox from "@/components/table/upfile.vue"
import batch from "@/components/table/batch.vue"
import { useUserStoreHook } from "@/store/modules/user"
import { ElMessage, ElMessageBox } from "element-plus"
// import { relevanceUserAdd, directorVerifyFinish, createUserVerifyFinish } from "@/api/meeting"
import { batchDivisionResponsible, batchDivisionDepartment, responsibleEdit } from "@/api/letters"

const { userId, username, rolesName } = useUserStoreHook()
const tabCombox = ref<typeof tabCom>()

onMounted(() => {
  init()
})
// 接口请求配置
const operationApiA = ref<any>([
  { type: "add", interface: "/putLetters/insertOrUpdate" },
  { type: "update", interface: "/putLetters/insertOrUpdate" },
  { type: "search", interface: "/putLetters/selectAll" },
  { type: "delete", interface: "/putLetters/deleteByIds" },
  { type: "svg", interface: "/putLetters/export" },
  { type: "uploadFile", interface: "/putLetters/importData" },
  { type: "downloadTem", interface: "/putLetters/downloadTemplate" }
])
//#region  添加按钮所有逻辑
// 添加按钮
const addButtonList = [
  {
    name: "总监审核",
    type: "CloseTask",
    show: {
      name: "lettersState",
      value: 1
    }
  },
  {
    name: "部门审核",
    type: "validation",
    show: {
      name: "lettersState",
      value: 2
    }
  },
  {
    name: "主办人审核",
    type: "infill",
    show: {
      name: "lettersState",
      value: 4
    }
  }
]
const tablerow = ref() // 当前操作表单数据
// 按钮回调
const buttonMoudle = (type: string, row: any, Face: string) => {
  tablerow.value = row
  console.log(type, row, "-*-buttonMoudle")
  switch (type) {
    case "CloseTask": //总监审核
      CloseTaskFn()
      break
    case "validation": // 部门审核
      validationFn()
      break

    case "infill": // 主办人审核
      infillFn()
      break
  }
}
let dialogVisible = ref(false) // 填写反馈行动项进展弹框
let actionItemEvolve = ref("") // 行动项进展
// 填写反馈行动项进展 方法
const infillFn = () => {
  // console.log("infillFn", userId)
  // 当前还没验证
  if (tablerow.value.lettersState == 4) {
    let batchDivisionInfoo = tablerow.value.batchDivisionInfo ? JSON.parse(tablerow.value.batchDivisionInfo) : {}
    if (userId == batchDivisionInfoo.sponsor) {
      dialogVisible.value = true
    } else {
      ElMessage.error("你不是该审核人~")
    }
  } else {
    if (tablerow.value.lettersState == 3) {
      ElMessage({
        message: "已操作",
        type: "warning"
      })
    } else {
      ElMessage({
        message: "还没到当前步骤",
        type: "warning"
      })
    }
  }
}
// 重置数据
const resetForm = () => {
  actionItemEvolve.value = ""
}
// 确认反馈
const handleCreate = () => {
  if (!actionItemEvolve.value) {
    ElMessage.error("处理方式不能为空")
    return
  }
  responsibleEdit({
    handlingMethod: actionItemEvolve.value,
    id: tablerow.value.id
  }).then((res) => {
    console.log(res, "---res")

    if (res.code == 200) {
      ElMessage({ message: "提交成功", type: "success" })
      tabCombox.value.resetSearch()
      dialogVisible.value = false
      resetForm()
    }
  })
}

// 部门分发参数
let zbFfData = reactive({
  sponsorUserId: "", // 主办人id
  dialogVisible: false // 弹框
})
// 重置
const resetFormzbFfData = () => {
  zbFfData.dialogVisible = false
  zbFfData.sponsorUserId = ""
}
// 确认部门分发
const validationFnConfim = () => {
  if (!zbFfData.sponsorUserId) {
    ElMessage.error("请选中主办人~")
    return
  }
  batchDivisionDepartment({
    id: tablerow.value.id,
    sponsorUserId: zbFfData.sponsorUserId
  }).then((res) => {
    if (res.code == 200) {
      ElMessage({ message: "提交成功", type: "success" })
      resetFormzbFfData()
      tabCombox.value.resetSearch()
    }
  })
}

// 部门审核
const validationFn = () => {
  // 当前还没验证
  if (tablerow.value.lettersState == 2) {
    let batchDivisionInfoo = tablerow.value.batchDivisionInfo ? JSON.parse(tablerow.value.batchDivisionInfo) : {}
    if (userId == batchDivisionInfoo.department) {
      zbFfData.dialogVisible = true
    } else {
      ElMessage.error("你不是该审核人~")
    }
  } else {
    if (tablerow.value.lettersState < 2) {
      ElMessage({
        message: "还没到当前步骤",
        type: "warning"
      })
    } else {
      ElMessage({
        message: "已操作",
        type: "warning"
      })
    }
  }
}
// 总监分发参数
let zjFfData = reactive({
  distributionType: 1, // 分发类型
  distributionUserId: "", // 分发人id
  dialogVisible: false // 弹框
})
// 重置
const resetFormzjFfData = () => {
  zjFfData.dialogVisible = false
  zjFfData.distributionType = 1
  zjFfData.distributionUserId = ""
}
// 确认总监审核
const CloseTaskFnConfim = () => {
  if (!zjFfData.distributionUserId) {
    ElMessage.error("请选中处理人~")
    return
  }
  batchDivisionResponsible({
    id: tablerow.value.id,
    ...zjFfData
  }).then((res) => {
    if (res.code == 200) {
      ElMessage({ message: "提交成功", type: "success" })
      resetFormzjFfData()
      tabCombox.value.resetSearch()
    }
  })
}

// 总监审核
const CloseTaskFn = () => {
  // 当前还没验证
  if (tablerow.value.lettersState == 1) {
    let batchDivisionInfoo = tablerow.value.batchDivisionInfo ? JSON.parse(tablerow.value.batchDivisionInfo) : {}
    if (userId == batchDivisionInfoo.director) {
      zjFfData.dialogVisible = true
    } else {
      ElMessage.error("你不是该审核人~")
    }
  } else {
    ElMessage({
      message: "已操作",
      type: "warning"
    })
  }
}

//#endregion

let iszjFfa = ref(0) // 当前分发类型
let fenfaVal = ref("") // 分发值
let batchDivisionInfoVal = ref({}) // 分发只

watch(fenfaVal, (newVal) => {
  if (iszjFfa.value == 0) {
    batchDivisionInfoVal.value = { director: newVal, department: "", sponsor: "" }
  } else {
    batchDivisionInfoVal.value = { director: "", department: "", sponsor: newVal }
  }
})

// 搜索配置
const searchDataListJy = [
  { name: "id", title: "id" },
  { name: "projectName", title: "项目名称" },
  { name: "communicateChannelNum", title: "通讯渠道号" },
  { name: "fileType", title: "文件类型" },
  { name: "theme", title: "主题" },
  {
    name: "isReply",
    title: "是否回复",
    type: "select",
    list: [
      { value: 0, label: "否", name: "否", id: 0 },
      { value: 1, label: "是", name: "是", id: 1 }
    ]
  },
  { name: "otherComeOrder", title: "对方来文号" },
  { name: "startTime", title: "开始时间", type: "datetime" },
  { name: "endTime", title: "结束时间", type: "datetime" }
]
// 添加配置
const searchDataListJyEdit = [
  { name: "receivingUnit", title: "发文单位	" },
  { name: "projectName", title: "项目名称	" },
  { name: "communicateChannelNum", title: "通讯渠道号" },
  { name: "fileType", title: "文件类型" },
  { name: "theme", title: "主题" },
  { name: "pageNum", title: "页数" },
  { name: "otherComeOrder", title: "对方来文号" },
  { name: "annexFileUrl", title: "附件", type: "file", prop: "annexFileName" },
  {
    name: "isReply",
    title: "是否回复",
    type: "select",
    list: [
      { value: 0, label: "否", name: "否", id: 0 },
      { value: 1, label: "是", name: "是", id: 1 }
    ]
  },
  { name: "replyEndDate", title: "回复时间", type: "datetime" },
  // { name: "batchDivisionInfo", title: "批分信息", type: "batch" },
  { name: "batchDivisionInfo", title: "批分信息", type: "batchNew" },
  // { name: "responsible", title: "总监",type:'user' },
  { name: "remarks", title: "备注" }
]
// 表单配置
const tableDataRuleA = ref([
  { prop: "id", label: "id" },
  { name: "abc", label: "发文单位" },
  { prop: "projectName", label: "项目名称" },
  { prop: "communicateChannelNum", label: "通讯渠道号" },
  { prop: "fileType", label: "文件类型" },
  { prop: "theme", label: "主题" },
  { prop: "pageNum", label: "页数" },
  { prop: "otherComeOrder", label: "对方来文号" },
  { prop: "annexFileName", label: "附件", type: "filename", assoc: "annexFileUrl" },
  {
    prop: "isReply",
    label: "是否回复",
    type: "select",
    list: [
      { value: 0, label: "否", name: "否", id: 0 },
      { value: 1, label: "是", name: "是", id: 1 }
    ]
  },
  { prop: "replyEndDate", label: "回复时间", type: "time" },
  { prop: "batchDivisionInfo", label: "批分信息", slot: "batchbox", width: "300px" },
  { prop: "handleRes", label: "处理结果" },
  { prop: "remarks", label: "备注" }
  // {prop: 'operate',label: '操作'},
])
// 初始化
const init = () => {}
// 表单刷新
const Refresh = () => {
  //用户数据概览
}
// 搜索回调
const searchCallback = (search: any) => {}
const loading = ref<boolean>(false)
const gailan = ref<any>({})
const gethomeStatisticsStar = (obj: any = {}) => {
  // loading.value = true
  // gethomeStatistics(obj).then((res: any) => {
  //   gailan.value = res.data
  //   loading.value = false
  // })
}

// 时间选择限定范围
const chooseTimeChange = (time: any) => {
  const starTime = JSON.parse(JSON.stringify(time[0]))
  const endTime = JSON.parse(JSON.stringify(time[1]))
  const minTime = new Date(insertStr(insertStr(starTime, 4, "-"), 7, "-")).getTime()
  const maxTime = new Date(insertStr(insertStr(endTime, 4, "-"), 7, "-")).getTime()
  const allow = 2592000000 //30天
  if (maxTime - minTime > allow) {
    ElMessage.warning("选择范围请在30天以内!")
    chaxunState.value = false
  } else {
    chaxunState.value = true
  }
}
</script>
<style scoped lang="scss">
.search-wrapper {
  margin: 0 auto;
  width: 98.5%;
  margin-top: 10px;
}
</style>
